﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Cyss.Core;
using Cyss.Core.Repository;
using Common.Api.Entitys;
using Common.Api.Dtos;
using Cyss.Core.Repository.EF;
using System.IO;
using System.Threading.Tasks;

namespace Common.Api.Services
{
    /// <summary>
    /// 文件表服务
    /// </summary>
    public class DownloadService : BaseService<Download>
    {
        #region 字段
        /// <summary>
        /// 文件表仓储
        /// </summary>
        private readonly IRepository<Download> _fileRepository;

        private string PathRoot = @"D:\Code\Cyss.Net\Webs\Blazor\CyssBlazor.WebAssembly\wwwroot\";

        #endregion

        #region 构造函数

        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="fileRepository">文件表 仓储</param>
        /// <param name="eventPublisher">事件发布者</param>
        public DownloadService(IRepository<Download> fileRepository) : base(fileRepository)
        {
            _fileRepository = fileRepository;
        }

        #endregion

        #region 文件表方法

        /// <summary>
        /// 获取文件
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual async Task<byte[]> GetFielBytesAsync(Download entity)
        {
            var path = GetFilePath(entity);
            if (!System.IO.File.Exists(path))
            {
                return null;
            }
            return await System.IO.File.ReadAllBytesAsync(path);
        }


        /// <summary>
        /// 插入文件
        /// </summary>
        public virtual async Task InsertFile(Download entity, byte[] fileBinary)
        {
            this.Insert(entity);
            await SaveFileAsync(entity, fileBinary);
        }

        /// <summary>
        /// Save picture on file system
        /// </summary>
        /// <param name="pictureId">Picture identifier</param>
        /// <param name="pictureBinary">Picture binary</param>
        /// <param name="mimeType">MIME type</param>
        private async Task SaveFileAsync(Download entity, byte[] fileBinary)
        {
            await System.IO.File.WriteAllBytesAsync(GetFilePath(entity), fileBinary);
        }

        private string GetFilePath(Download entity)
        {
            string filename = $"{GetFolder(entity.CreateDateTime)}/{entity.Id}{entity.Extension}";
            return Path.Combine(filename);
        }

        private string GetFolder(DateTime date)
        {
            var path = $"{PathRoot}files/{date.Year}/{date.Month}/{date.Day}";
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            return path;
        }

        /// <summary>
        ///  获取所有的  文件表
        /// </summary>
        /// <param name="predicate">查询条件</param>
        /// <param name="IsNoTracking">是否进行实体跟踪,如果查询的对象不用于修改更新默认即可，实体跟踪会消耗资源</param>
        /// <returns>文件表集合</returns>
        public virtual IList<Download> GetFiles(Expression<Func<Download, bool>> predicate = null, bool IsNoTracking = true)
        {
            var query = _fileRepository.Table;
            if (IsNoTracking)
            {
                query = _fileRepository.TableNoTracking;
            }
            if (predicate != null)
            {
                query = query.Where(predicate);
            }

            return query.ToList();

        }
        #endregion

    }
}

